﻿using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Linq;

namespace Model.Movie
{
    internal class WriteBackdrops
    {
        private MovieDatabaseEntities entities;

        public WriteBackdrops(MovieDatabaseEntities entities)
        {
            this.entities = entities;
        }

        internal void Insert(Movies movie, IEnumerable<byte[]> importItems)
        {
            if (movie.Backdrops.Count > 0)
                Delete(movie.Id);

            foreach (var item in importItems)
            {
                var backdrop = BackdropsConverter.GetEntity(item);

                if (backdrop != null)
                {
                    movie.Backdrops.Add(backdrop);
                }
            } 
            
            entities.SaveChanges();
        }

        public void Delete(int id)
        {
            var backdrops = entities.Backdrops.Where(m => m.Movies_Id == id);

            foreach (var backdrop in backdrops)
            {
                entities.Backdrops.DeleteObject(backdrop);
                entities.SaveChanges();      
            }                     
        }
    }
}
